package com.acme.domain.email.impl;

import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.acme.domain.email.Email;
import com.acme.domain.email.Queue;

public class QueueImpl implements Queue {

    List<Email> mails = new LinkedList<Email>();
    volatile boolean close;

    @Override
    public void addEmail(final Email email) {
	if (close) {
	    return;
	}
	synchronized (mails) {
	    mails.add(email);
	    mails.notify();
	}
    }

    @Override
    public void close() {
	close = true;
    }

    @Override
    public Email getEmail() {
	synchronized (mails) {
	    if (mails.isEmpty()) {
		try {
		    while (mails.isEmpty()) {
			mails.wait();
		    }
		} catch (InterruptedException ex) {
		    Logger.getLogger(QueueImpl.class.getName()).log(
			    Level.SEVERE, null, ex);
		    return null;
		}
	    }
	    Email email = mails.remove(0);
	    return email;
	}
    }

    @Override
    public boolean isClose() {
	return close;
    }

    @Override
    public boolean isEmpty() {
	synchronized (mails) {
	    return mails.isEmpty();
	}
    }
}
